import { _decorator, AudioClip, Collider2D, Component, Node, ParticleSystem2D, tween, v3 } from 'cc';
import { AudioManager } from 'db://assets/Scripts/Framework/Managers/AudioManager';
import { Item } from '../Item';
const { ccclass, property } = _decorator;

@ccclass('Box')
export class Box extends Component {

    @property
    size = 1;

    @property
    doorX = 0;

    @property
    doorY = 0;

    @property
    canCook = false;

    @property
    isOpen = false;

    @property(AudioClip)
    clip: AudioClip;

    @property(ParticleSystem2D)
    particle: ParticleSystem2D;

    @property([Node])
    doors: Node[] = [];

    @property([Collider2D])
    colliders: Collider2D[] = [];

    isTween = false;

    start() {
        this.schedule(this.CheckIndex, 0.1);
    }

    update(deltaTime: number) {

    }

    Click() {
        if (this.isTween) return;
        this.isOpen = !this.isOpen;
        if (this.doors.length == 2) {
            this.doors[0].active = !this.isOpen;
            this.doors[1].active = this.isOpen;
        }
        else {
            this.isTween = true;
            let pos = v3(this.isOpen ? this.doorX : -this.doorX, this.isOpen ? this.doorY : -this.doorY);
            tween(this.doors[0])
                .by(1, { position: pos })
                .call(() => { this.isTween = false; })
                .start();
        }
        for (let i = 0; i < this.colliders.length; i++) {
            const element = this.colliders[i];
            element.enabled = this.isOpen;
        }
        if (this.clip) AudioManager.Instance.PlaySFX(this.clip);
        if (this.particle) {
            if (this.isOpen) this.particle.stopSystem();
            else if (this.getComponentInChildren(Item)) this.particle.resetSystem();
        }
    }

    CheckIndex() {
        let arrY: (Node | number)[][] = [];
        for (let i = 0; i < this.node.children.length; i++) {
            const element = this.node.children[i];
            arrY.push([element, element.getPosition().y]);
        }
        arrY.sort((a, b) => { return b[1] as number - (a[1] as number) });
        for (let i = 0; i < arrY.length; i++) {
            const element = arrY[i][0] as Node;
            element.setSiblingIndex(i);
        }
    }
}


